﻿using AutoMapper;
using MediatR;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Infrstructre.Interface;
using RBAC_Uthorization.Read.API.Application.Command.RoleCommand;
using RBAC_Uthorization.Read.API.DTO;
using RBAC_Uthorization.Read.API.DTO.Response.Role;

namespace RBAC_Uthorization.Read.API.Application.CommandHandlers.RoleHandler
{
    public class RoleFindCommandHandlers : IRequestHandler<RoleFindCommand, ApiResult<RoleFindDto>>
    {
        private readonly IRoleRepository _roleRepository;
        private readonly ILogger<RoleFindCommandHandlers> _logger;
        private readonly IMapper _mapper;

        public RoleFindCommandHandlers(IRoleRepository roleRepository, ILogger<RoleFindCommandHandlers> logger, IMapper mapper)
        {
            _roleRepository = roleRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult<RoleFindDto>> Handle(RoleFindCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var rolelist = await _roleRepository.GetAllAsunc(x => x.id == request.id && x.offic_id == request.offlc_id && x.sys_id == request.sys_id && x.del_flag == 0);
                var role = rolelist.FirstOrDefault();
                if (role == null)
                {
                    return new ApiResult<RoleFindDto>(ResultCode.Error, "角色不存在");
                }
                var roleDto = _mapper.Map<RoleFindDto>(role);
                return new ApiResult<RoleFindDto>() { Data = roleDto };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询角色失败");
                return new ApiResult<RoleFindDto>(ResultCode.Error, "查询角色失败");
            }

        }
    }
   
}
